// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/thread.h>
#include <zencore/timer.h>

#include <zencore/testing.h>

#if ZEN_PLATFORM_WINDOWS
#	include <zencore/windows.h>
#elif ZEN_PLATFORM_LINUX
#	include <time.h>
#	include <unistd.h>
#endif

namespace zen {

uint64_t
GetHifreqTimerValue()
{
	uint64_t Timestamp;

#if ZEN_PLATFORM_WINDOWS
	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);

	Timestamp = li.QuadPart;
#else
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	Timestamp = (uint64_t(ts.tv_sec) * 1000000ull) + (uint64_t(ts.tv_nsec) / 1000ull);
#endif

	return Timestamp;
}

uint64_t
InternalGetHifreqTimerFrequency()
{
#if ZEN_PLATFORM_WINDOWS
	LARGE_INTEGER li;
	QueryPerformanceFrequency(&li);

	return li.QuadPart;
#else
	return 1000000ull;
#endif
}

uint64_t			QpcFreq	  = InternalGetHifreqTimerFrequency();
static const double QpcFactor = 1.0 / InternalGetHifreqTimerFrequency();

uint64_t
GetHifreqTimerFrequency()
{
	return QpcFreq;
}

double
GetHifreqTimerToSeconds()
{
	return QpcFactor;
}

uint64_t
GetHifreqTimerFrequencySafe()
{
	if (!QpcFreq)
	{
		QpcFreq = InternalGetHifreqTimerFrequency();
	}

	return QpcFreq;
}

//////////////////////////////////////////////////////////////////////////

uint64_t detail::g_LofreqTimerValue = GetHifreqTimerValue();

void
UpdateLofreqTimerValue()
{
	detail::g_LofreqTimerValue = GetHifreqTimerValue();
}

uint64_t
GetLofreqTimerFrequency()
{
	return GetHifreqTimerFrequencySafe();
}

//////////////////////////////////////////////////////////////////////////
//
// Testing related code follows...
//

#if ZEN_WITH_TESTS

void
timer_forcelink()
{
}

#endif

}  // namespace zen
